/**
 * Created by chengming on 18/4/18.
 * version 1.0
 */
const BaseJsonAdapter = require('./base/BaseJsonAdapter');
const logger = require('../conf/logger');
const request = require('request-promise');
const cheerio = require('cheerio');
const moment = require('moment');
const urlTool = require('url');
const quaryString = require('querystring');
const server = require('../conf/server');
const iconv = require("iconv-lite");
const JSONSelect = require('JSONSelect');
const report = require('../exception/ErrorReport');
const vm = require('vm');

class JsonpAdapter extends BaseJsonAdapter{

	constructor(page, isTest){
		super(page, isTest);
	}

	async reqJson(){
		logger.debug('开始执行抓取->'+this.pageName);

		let query = urlTool.parse(this.requestUrl).query;
		let callbackFun = quaryString.parse(query).callback;

		const body = await this.doRequest();

		let decodeBody = iconv.decode(body, this.encoding).toString();

		global.jsonpRet = {};
		vm.runInThisContext(callbackFun+'=function(json){ jsonpRet = json }; '+ decodeBody);

		let ret = jsonpRet;
		delete global.jsonpRet;

		if(ret instanceof Array){
			return ret[0];
		}

		return ret;
	}
}

module.exports = JsonpAdapter;